<template>
	<view :style="{background: `#f7f8fc url(${imageBaseUrl}/detailsbj.png) no-repeat top center / 100% 447rpx`}">
		<!-- #ifdef MP-WEIXIN -->
		<view class="custom-nav">
			<view v-if="!type" class="back-btn" @click="navigateBack">
				<image class="back-btn-img" src="/static/images/xiajianimg.png"></image>
			</view>
			<view class="nav-title">政策详情</view>
		</view>
		<!-- #endif -->
		<view class="PolicyDetails" :class="{ 'no-scroll': type }">
			<view class="GuideDetailsTop">
				<view class="GuideDetailsTops">
					<view class="PolicyDocumentLiTitle">{{
          this.policyInfo.policyName
        }}</view>
					<view class="PolicyDocumentLiTag">
						<view class="PolicyDocumentLiTagli">{{
            this.policyInfo.policyRegion
          }}</view>
						<view class="PolicyDocumentLiTagli">{{
            this.policyInfo.policyPubdept
          }}</view>
						<view class="PolicyDocumentLiTagli">{{
            getDictLabel(this.policyInfo.policyType, this.policyType)
          }}</view>
						<view class="PolicyDocumentLiTagli">{{
            this.policyInfo.pubTime
          }}</view>
						<view v-if="this.policyInfo.isDeclare == 1" class="PolicyDocumentLiTagli">申报指南</view>
					</view>
				</view>
			</view>
			<view class="PolicyDetailsBot">
				<view class="gDetailsTop">
					<view class="gDetailsTopTitle">政策基本信息</view>
					<view class="gDetailsTopList">
						<view class="gDetailsTopListLi">
							<view class="gDetailsTopListLil">所属区划</view>
							<view class="gDetailsTopListLir">{{
              this.policyInfo.policyRegion
            }}</view>
						</view>
						<view class="gDetailsTopListLi">
							<view class="gDetailsTopListLil">发布单位</view>
							<view class="gDetailsTopListLir">{{
              this.policyInfo.policyPubdept
            }}</view>
						</view>
						<view class="gDetailsTopListLi">
							<view class="gDetailsTopListLil">发布日期</view>
							<view class="gDetailsTopListLir">{{
              this.policyInfo.pubTime
            }}</view>
						</view>
					</view>
				</view>
				<view class="gDetailsTop" style="padding-bottom: 250rpx">
					<view class="gDetailsTopTitle">政策详情</view>
					<view class="gDetailsTopContent" v-html="this.policyInfo.policyContent">
					</view>
					<view v-if="this.policyInfo.policyAnnexes && this.policyInfo.policyAnnexes.length > 0"
						class="annexes-section">
						<view class="annexes-title">附件：</view>
						<view class="annexes-list">
							<view v-for="(annex, index) in this.policyInfo.policyAnnexes" :key="index"
								class="annex-item" @click="openAnnex(annex.url)">
								{{ annex.name }}
							</view>
						</view>
					</view>

				</view>
			</view>
			<rightFixedReport />
			<rightShare :isFavourite="isFavourite" @clickFavouriteEvent="clickFavouriteEvent"
				@clickUnFavouriteEvent="clickUnFavouriteEvent" />
			<view class="PolicyDetailsEnd">
				<view class="PolicyDetailsEnds">AI智能评估，一键预测政策适配指数</view>
				<view class="PolicyDetailsEndx">
					<view :class="['PolicyDetailsEndxBtn', btnType ? 'PolicyDetailsEndxBtnDis' : '']"
						@click="getReporting">一键生成匹配报告</view>
				</view>
			</view>
			<view class="ZheZhao" v-if="type"></view>
			<view class="Reporting" v-if="type">
				<image :src="`${imageBaseUrl}/loading.gif`"></image>
				<view class="ReportingText">正在通过AI大模型生成...</view>
				<view class="PolicyDetailsbackBtn" @click="handlebackgetreport">后台生成</view>
			</view>
			<association :isShow="isShow" @changeAssociation="changeAssociation" />
		</view>
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="3000"></uni-popup-message>
		</uni-popup>
		<uni-popup ref="message2" type="message">
			<uni-popup-message :type="msgType" :message="messageText2" :duration="3000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	import rightFixedReport from "@/pages/components/rightFixedReport.vue";
	import rightShare from "@/pages/components/rightShare.vue";
	import association from "@/pages/components/association.vue";
	import {
		useStore
	} from 'vuex';
	import {
		DICT_TYPES
	} from '@/store/modules/dict';
	import {
		getDictLabel
	} from '@/utils/dict';
	import {
		guideDetail,
		matchPolicy,
		favoritePolicy,
		getDefaultCompany,
		isFavoritePolicy,
		deletePolicyCollect,
	} from "../../api/api.js";
	export default {
		components: {
			rightFixedReport,
			rightShare,
			association,
		},
		computed: {
			imageBaseUrl() {
				return this.$IMAGE_BASE_URL;
			}
		},
		data() {
			return {
				messageText: '后台生成完成，请在我的报告中查看',
				messageText2: '后台生成中，请稍后',
				msgType: 'warn',
				btnType: false,
				type: false,
				policyInfo: {},

				backbtn: false,

				policyLevel: [],
				policyType: [],
				industryType: [],

				flag: -1,

				isShow: false,

				isFavourite: false,
				userPolicyFavorite: {},

				score: -1
			};
		},
		onLoad(options) {
			if (options.id) {
				this.getDetail(options.id);
			}

			if (options.flag) {
				this.flag = options.flag;
			} else {
				this.flag = -1;
			}

			this.score =options.score?options.score:-1;
			console.log('score:',this.score)
		
			console.log("标志位", this.flag);

			this.getDictData();

			console.log("policyInfo", this.policyInfo);
		},

		methods: {
			getDictLabel,
			navigateBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 获取是否收藏
			async getFavourite() {
				try {
					if (this.policyInfo && this.policyInfo.id) {
						const res = await isFavoritePolicy(this.policyInfo.id);
						if (res.code === 0) {
							console.log("收藏状态", res.data);
							if (res.data) {
								this.isFavourite = true;
								this.userPolicyFavorite = res.data;
							} else {
								this.isFavourite = false;
							}
						}
					}
				} catch (error) {
					console.error("获取收藏状态失败:", error);
				}
			},

			async clickUnFavouriteEvent() {
				console.log("点击取消收藏");
				// 调用取消收藏接口
				const res = await deletePolicyCollect(this.userPolicyFavorite.id);
				if (res.code === 0) {
					uni.showToast({
						title: "取消收藏成功",
					});
					this.getFavourite();
				}
			},

			clickFavouriteEvent() {
				console.log("点击分享", this.policyInfo);
				// 调用收藏接口

				const data = {
					policyId: this.policyInfo.id,
					favoriteType: this.policyInfo.isDeclare,
				};
				favoritePolicy(data).then((res) => {
					if (res.code === 0) {
						uni.showToast({
							title: "收藏成功",
							icon: "success",
						});
						this.getFavourite();
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none",
						});
					}
				});
			},

			changeAssociation() {
				this.isShow = false;
			},
			async handlebackgetreport(){
				this.backbtn = true;
				this.type = false;	
				this.btnType = true;
				this.$refs.message2.open()	// await this.getReporting();

			},
			async getReporting(types) {
				let companyInfo = {};

				if (this.flag == 1) {
					console.log("详情页调用");
					const res = await getDefaultCompany();
					console.log("默认企业", res);
					if (res.data == null) {
						this.isShow = true;
						uni.showToast({
							title: "请关联企业",
							icon: "none",
						});
					} else {
						companyInfo = res.data;
						uni.setStorageSync("companyInfo", companyInfo);
						this.matchPolicy(companyInfo, types);
					}
				} else {
					companyInfo = uni.getStorageSync("companyInfo");
					this.matchPolicy(companyInfo, types ,this.score);
				}
			},
			async matchPolicy(companyInfo, types ,score) {
				// 调用匹配政策接口
				// if (types === 'async') {
				// 	this.btnType = true
				// 	// this.$refs.message.open();
				// 	const res = await matchPolicy(companyInfo.id, this.policyInfo.id ,score);
				// 	const {
				// 		code
				// 	} = res
				// 	if (code === 0) {
				// 		this.btnType = false
				// 		this.$refs.message.open();
				// 	}
				// } else {
					this.type = true;
					const res = await matchPolicy(companyInfo.id, this.policyInfo.id, score);
					if (res.code === 0) {
						this.btnType = false;
						uni.setStorageSync("curReport", res.data);
						if (this.backbtn) {
							this.$refs.message.open();
							return;
						}else{
							uni.navigateTo({
							url: "/pages/reportDetails/index",
							success: () => {
								this.type = false;
							}
						});
						}

					} else {
						this.type = false;
						uni.showToast({
							title: res.msg,
						});
					}
				// }
			},

			async getDetail(id) {
				try {
					const res = await guideDetail(id);
					console.log("政策详情数据:", res);
					if (res.code === 0) {
						this.policyInfo = res.data;
						// 获取到政策信息后，再获取收藏状态
						this.getFavourite();
					}
				} catch (error) {
					console.error("获取政策详情失败:", error);
				}
			},

			// 从Vuex获取字典数据
			async getDictData() {
				const store = useStore();

				// 加载政策层级
				this.policyLevel = await store.dispatch('dict/loadDict', DICT_TYPES.POLICY_LEVEL);

				// 加载行业分类
				this.industryType = await store.dispatch('dict/loadDict', DICT_TYPES.INDUSTRY_TYPE);

				// 加载政策类型
				this.policyType = await store.dispatch('dict/loadDict', DICT_TYPES.POLICY_TYPE);
			},
			openFile(url) {
				const fileExt = url.split(/[?#]/)[0].split('.').pop().toLowerCase();
				const wxSupportedTypes = [
					'pdf',
					'doc', 'docx',
					'xls', 'xlsx',
					'ppt', 'pptx',
					'txt'
				];
				if (!wxSupportedTypes.includes(fileExt)) {
					wx.showModal({
						title: '格式不支持',
						content: '请复制链接到浏览器查看',
						success: () => wx.setClipboardData({
							data: url
						})
					});
					return;
				}
				wx.showLoading({
					title: '加载中...',
					mask: true
				});
				wx.downloadFile({
					url: url,
					success: (res) => {
						wx.hideLoading();
						if (res.statusCode !== 200) {
							throw new Error(`HTTP ${res.statusCode}`);
						}
						wx.openDocument({
							filePath: res.tempFilePath,
							fileType: fileExt,
							success: () => console.log('打开成功'),
							fail: (err) => {
								console.error('[openDocument] 失败:', err);
								this.handleIOSFallback(url);
							}
						});
					},
					fail: (err) => {
						wx.hideLoading();
						console.error('[downloadFile] 失败:', err);
						this.handleIOSFallback(url);
					}
				});
			},
			handleIOSFallback(url) {
				wx.showModal({
					title: '提示',
					content: '文件打开失败，是否尝试以下方法去浏览器打开？',
					confirmText: '复制链接',
					success: (res) => {
						if (res.confirm) {
							wx.setClipboardData({
								data: url,
								success: () => wx.showToast({
									title: '链接已复制'
								})
							});
						}
					}
				});
			},
			openAnnex(url) {
				// if (!url?.startsWith('https://')) {
				//   wx.showToast({ title: '链接不安全', icon: 'none' });
				//   return;
				// }

				const systemInfo = wx.getSystemInfoSync();

				// iOS 特殊提示
				if (systemInfo.platform === 'ios') {
					wx.showModal({
						title: 'iOS 用户注意',
						content: '部分文件需要手动保存查看，是否继续？',
						success: (res) => res.confirm && this.openFile(url)
					});
				} else {
					this.openFile(url);
				}
			}
		},
	};
</script>

<style lang="scss">
	.custom-nav {
		height: 88rpx;
		padding: 60rpx 30rpx 30rpx;
		background: #315bfe;
		position: relative;

		.nav-title {
			text-align: center;
			line-height: 88rpx;
			padding: 30rpx 0 0;
		}
	}

	.back-btn {
		position: absolute;
		left: 30rpx;
		bottom: 27rpx;

		.back-btn-img {
			width: 30rpx;
			height: 18rpx;
			transform: rotate(90deg);
		}
	}

	.PolicyDetails {
		&.no-scroll {
			height: 100vh;
			overflow: hidden;
		}

		.GuideDetailsTop {
			padding: 30rpx 24rpx 0;

			.GuideDetailsTops {
				padding: 28rpx 33rpx;
				border-radius: 20rpx;
				margin: 0 0 27rpx;
				background: #ffffff;

				.PolicyDocumentLiTitle {
					font-size: 32rpx;
					color: #202020;
				}

				.PolicyDocumentLiTag {
					display: flex;
					justify-content: flex-start;
					flex-wrap: wrap;
					padding: 15rpx 0;
					gap: 15rpx;

					.PolicyDocumentLiTagli {
						padding: 13rpx;
						// height: 40rpx;
						line-height: 30rpx;
						font-size: 24rpx;
						color: #4e5262;
						background: #ecf3fc;
						margin-right: 0;
						border-radius: 10rpx;
					}
				}
			}
		}

		.PolicyDetailsBot {
			padding: 1rpx 24rpx 0;
			background: #f7f8fc;
			border-radius: 20rpx 20rpx 0 0;

			.gDetailsTop {
				margin: 30rpx 0 0;
				padding: 32rpx;
				background: #ffffff;
				border-radius: 20rpx;

				.gDetailsTopTitle {
					font-size: 28rpx;
					color: #202020;
					padding-left: 35rpx;
					background: url("/static/images/sanjiao.png") no-repeat left center / 17rpx 21rpx;
				}

				.gDetailsTopContent {
					font-size: 28rpx;
					color: #4e5262;
					line-height: 55rpx;
				}

				.gDetailsTopList {
					padding: 20rpx 0 0;

					.gDetailsTopListLi {
						display: flex;
						line-height: 55rpx;
						justify-content: space-between;

						.gDetailsTopListLil {
							flex: none;
							font-size: 28rpx;
							color: #4e5262;
						}

						.gDetailsTopListLir {
							font-size: 28rpx;
							color: #202020;
							margin-left: 20rpx;
						}
					}
				}
			}
		}
	}

	.PolicyDetailsEnd {
		position: fixed;
		bottom: 0;
		left: 50%;
		margin-left: -50%;
		width: 100%;
		height: 273rpx;
		padding: 47rpx 44rpx 0 37rpx;
		box-sizing: border-box;
		background: url("/static/images/policybj1.png") no-repeat center / 100% 273rpx;

		.PolicyDetailsEnds {
			height: 86rpx;
			line-height: 86rpx;
			font-size: 28rpx;
			color: #202020;
			padding-left: 93rpx;
			background: url("/static/images/reportimg1.png") no-repeat left center / 90rpx 81rpx;
		}

		.PolicyDetailsEndx {
			display: flex;
			justify-content: space-between;
			padding-left: 7rpx;

			.PolicyDetailsEndxBtn {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				background: #2f59fe;
				border-radius: 20rpx;
				font-size: 32rpx;
				color: #f7f8fc;
				text-align: center;

				&.PolicyDetailsEndxBtnDis {
					pointer-events: none;
					background: #999999;
				}
			}
		}
	}

	.Reporting {
		position: fixed;
		left: 50%;
		margin-left: -225rpx;
		top: 50%;
		margin-top: -200rpx;
		width: 450rpx;
		height: 450rpx;
		z-index: 99;
		border-radius: 20rpx;
		background: #ffffff;

		image {
			display: block;
			width: 433rpx;
			height: 292rpx;
			margin: auto;
		}

		.ReportingText {
			font-size: 32rpx;
			color: #4e5262;
			text-align: center;
		}

		.PolicyDetailsbackBtn {
   			width: 80%;
   			height: 70rpx;
    		line-height: 70rpx;
    		background: #2f59fe;
    		border-radius: 20rpx;
    		font-size: 32rpx;
    		color: #f7f8fc;
    		text-align: center;
    		margin: 20rpx auto 0;

  }
	}

	.ZheZhao {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 98;
		background: rgba(0, 0, 0, 0.5);
	}

	.annexes-section {
		margin-top: 30rpx;
		padding-top: 20rpx;
		padding-bottom: 50rpx;
		border-top: 1rpx solid #eee;

		.annexes-title {
			font-size: 28rpx;
			color: #202020;
			margin-bottom: 15rpx;
		}

		.annexes-list {
			.annex-item {
				font-size: 28rpx;
				color: #0947c1;
				line-height: 50rpx;
				padding: 10rpx 0;
				text-decoration: underline;
				cursor: pointer;

				&:active {
					opacity: 0.8;
				}
			}
		}
	}

	.uni-popup {
		top: 15vh !important;
	}

	.uni-popup__warn {
		border-width: 0 !important;
		background-color: rgba(9, 71, 193, 1) !important;
	}

	.uni-popup__warn-text {
		color: #ffffff !important;
	}

	/* 自定义消息弹窗样式 */
	.uni-popup-message {
		padding: 0 !important;
		border-radius: 20rpx !important;
		box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08) !important;
		transform-origin: top;
		animation: messageFloat 0.4s cubic-bezier(0.215, 0.61, 0.355, 1) !important;
		max-width: 80% !important;
		margin: 0 auto !important;
		overflow: hidden !important;
		opacity: 0.97 !important;
		display: flex !important;
		align-items: center !important;
		justify-content: center !important;

		.uni-popup-message-text {
			font-size: 28rpx !important;
			color: #ffffff !important;
			font-weight: 500 !important;
			letter-spacing: 0.5rpx !important;
			line-height: 1.5 !important;
			text-align: center !important;
			white-space: nowrap !important;
			overflow: hidden !important;
			text-overflow: ellipsis !important;
			margin: 0 0 0 -3rpx !important;
			width: 100% !important;
			display: flex !important;
			align-items: center !important;
			justify-content: center !important;
		}
	}
</style>